package com.netcracker.educenter.filestorage.datasource.connection;

import com.netcracker.educenter.filestorage.configurator.Configurator;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionPool {

    private static final Logger log = Logger.getLogger(ConnectionPool.class);

    private static final String DRIVER_NAME = Configurator.getConfigurator().getDriver();
    private static final String URL = Configurator.getConfigurator().getUrl();
    private static final String USER = Configurator.getConfigurator().getUser();
    private static final String PASSWORD = Configurator.getConfigurator().getPassword();

    private static final ConnectionPool INSTANCE = new ConnectionPool();

    private static final int MAX_COUNT_OF_CONNECTION = 10;

    private Connection[] connections = new Connection[MAX_COUNT_OF_CONNECTION];
    private int used = 0;

    private ConnectionPool() {

        try {
            Class.forName(DRIVER_NAME);

            for (int i = 0; i < 10; i++){
                connections[i] = DriverManager.getConnection(URL, USER, PASSWORD);
            }
        } catch (ClassNotFoundException e) {
            log.error("Cannot load driver", e);
        } catch (SQLException e) {
            log.error("Cannot get connection", e);
        }
    }

    public static ConnectionPool getConnectionPool() {

        return INSTANCE;
    }

    public synchronized Connection getConnection() {

        while (used == 10){
            try {
                wait();
            } catch (InterruptedException e) {
                log.error("Error in getConnection", e);
            }
        }

        Connection connection = null;

        for (int i = 0; i < connections.length; i++) {
            if (connections[i] != null) {
                connection = connections[i];
                connections[i] = null;
                used++;
                break;
            }
        }

        return connection;
    }

    public synchronized void releaseConnection(Connection connection) {

        for (int i = 0; i < connections.length; i++) {
            if (connections[i] == null){
                connections[i] = connection;
                used--;
                break;
            }
        }

        notifyAll();
    }
}
